﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using mBlog.Services;
using mBlog.ViewModels;
using mBlog.Extensions;
using mBlog.Admin.ViewModels;
using mBlog.Models;

namespace mBlog.Admin.Controllers
{
    public class PostController : AdminBaseController
    {
        private IPostService postService;
        private ICategoryService categoryService;

        public PostController(IPostService postService, ICategoryService categoryService)
        {
            this.postService = postService;
            this.categoryService = categoryService;
        }

        public ActionResult Delete(long postId)
        {
            postService.Delete(postId);
            return RedirectToAction("List");
        }

        public ActionResult List(int? page)
        {
            var postListView = new ListView<PostSummaryView>();
            var posts = postService.Get(page, ItemsPerPage).ToList();

            postListView.List = (from p in posts
                                 select new PostSummaryView
                                 {
                                     ID = p.ID,
                                     Name = p.Title,
                                     PostedTime = p.PostedTime.ToString(),
                                     IsPublished = p.IsPublished,
                                     PublishedTime = p.PublishedTime.HasValue ? p.PublishedTime.Value.ToString() : string.Empty
                                     //CategoryName = p.Categories.First().Name,
                                     //CategoryUrl = Url.Action("View", "Category", new { urlName = p.Categories.First().UrlName })
                                 }).ToList();


            PagerView pager = new PagerView
                                  {
                                      PageCount = (int)Math.Ceiling((double)postService.Count() / (ItemsPerPage)),
                                      CurrentPage = page ?? 0,
                                      ActionName = "List",
                                      ControllerName = "Post"
                                  };

            postListView.Pager = pager;
            return View(postListView);
        }

        public ActionResult PostsByCategory(int categoryId, int? page)
        {
            Category category = categoryService.Single(categoryId);
            var lvPosts = new ListView<Post>
                              {
                                  Title = "Posts under :" + category.Name,
                                  List = category.Posts.AsQueryable()
                                      .AtPage<Post>(page, ItemsPerPage).ToList()
                              };

            PagerView pager = new PagerView
                                  {
                                      PageCount = (int)Math.Ceiling((double)category.Posts.Count() / (ItemsPerPage)),
                                      CurrentPage = page ?? 0,
                                      ActionName = "PostsByCategory",
                                      ControllerName = "Post"
                                  };

            lvPosts.Pager = pager;
            return View(lvPosts);
        }


        [HttpGet]
        public ActionResult Add()
        {
            AddPostViewModel addModel = new AddPostViewModel { Categories = categoryService.Get() };


            return View(addModel);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Add(PostInput postInput)
        {
            var post = postInput.MapTo<Post>();
            post.Categories = new List<Category>();
            post.Categories.Add(categoryService.Single(postInput.CategoryUrlName));

            post.Tags = new List<Tag>();

            if (!string.IsNullOrEmpty(postInput.Tags))
            {
                post.Tags.Concat(
                                  (from tag in postInput.Tags.Split(';')
                                   select new Tag
                                   {
                                       Name = tag,
                                       UrlName = TagBuilder.CreateSanitizedId(tag),
                                       AddedTime = DateTime.Now,
                                       IsActive = true
                                   }).ToList()
                                );

            }
            postService.Add(post);

            return RedirectToAction("List");
        }

        [HttpGet]
        [Authorize]
        public ActionResult Edit(long postId)
        {
            Post post = postService.Single(postId);
            IList<Category> categories = categoryService.Get();

            PostEditViewModel pev = new PostEditViewModel { Post = post.MapTo<PostInput>(), Categories = categories };

            return View(pev);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(PostInput post)
        {

            Post p = post.MapTo<Post>();
            
            p.Categories = new List<Category>();
            p.Categories.Add(categoryService.Single(post.CategoryUrlName));
            
            if (p.IsPublished) p.PublishedTime = DateTime.Now;

            postService.Update(p);


            return RedirectToAction("Edit");
        }

    }
}
